/*
 * 项目名称:    wms-server-jeecg
 * 创建人员:    gongwenkai
 * 创建时间:    2023-09-26
 */
package org.jeecg.modules.flow.callback.outbound.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.business.doc.outbound.entity.WmsOutReceipt;
import org.jeecg.modules.business.doc.outbound.entity.WmsOutReceiptMaterial;
import org.jeecg.modules.business.doc.outbound.service.IWmsOutReceiptMaterialService;
import org.jeecg.modules.business.doc.outbound.service.IWmsOutReceiptService;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTask;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTaskMaterial;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskMaterialService;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskService;
import org.jeecg.modules.flow.callback.enums.DocumentStatusEnum;
import org.jeecg.modules.flow.callback.enums.OutboundStatusEnum;
import org.jeecg.modules.flow.callback.outbound.util.CommonOutboundUtil;
import org.jeecg.modules.flow.sys.common.BaseCustomBeanRun;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.jeecg.modules.flow.sys.service.WorkFlowService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 *横剪叫料（条料）备料 回调Bean
 *
 * @author gongwenkai
 * @version 1.0.0
 * @since 2023-09-26
 */
@RequiredArgsConstructor
@Component
public class OutBoundTaskHJJLTLPrepareBean<T> extends BaseCustomBeanRun<T> {

    private final IWmsOutReceiptTaskService wmsOutReceiptTaskService;

    private final IWmsOutReceiptTaskMaterialService wmsOutReceiptTaskMaterialService;

    private final IWmsOutReceiptService wmsOutReceiptService;

    private final IWmsOutReceiptMaterialService wmsOutReceiptMaterialService;

    private final WorkFlowService workFlowService;

    private final CommonOutboundUtil commonOutboundUtil;

    /**
     * 业务逻辑 横剪叫料（条料）备料
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void actureRun() {
        BaseFlowDto baseFlowDto = this.getBaseFlowDto();
        String taskId = baseFlowDto.getInfoId();
        //拿到创建出库单的数据
        baseFlowDto.translateClass(JSONObject.class);
        JSONObject jsonData= (JSONObject)baseFlowDto.getData();
        Boolean fromReceiptOrderFlag = jsonData.getBoolean("fromReceiptOrderFlag");
        if(fromReceiptOrderFlag!=null&&fromReceiptOrderFlag==true){
            //如果是从出库单流转过来的
            //判断并更新任务信息和状态
            //Boolean flag = updateTaskMaterial(jsonData.getString("receiptId"));
            Boolean completeFlag = commonOutboundUtil.checkOutTaskComplete(taskId);
            //如果已经全部出库，流转到下一个节点
            if(!completeFlag){
                baseFlowDto.setRunThenStop(true);
            }
        }
        // 当前前端调用业务需要你返回的
        baseFlowDto.setResult(Result.OK());
        // id是保存业务记录的id。用于生成业务流程信息记录
        baseFlowDto.setInfoId(taskId);
    }

//    /**
//     * 更新任务状态
//     */
//    public Boolean updateTaskMaterial(String receiptId) {
//        boolean taskOutFlag = true;
//        WmsOutReceipt wmsOutReceipt = wmsOutReceiptService.getById(receiptId);
//        if (Objects.isNull(wmsOutReceipt)) {
//            throw new JeecgBootException("出库单不存在!");
//        }
//        //出库任务id
//        String taskId = wmsOutReceipt.getWmsOutReceiptTaskId();
//        //出库任务-物料
//        List<WmsOutReceiptTaskMaterial> list = wmsOutReceiptTaskMaterialService.list(new LambdaQueryWrapper<WmsOutReceiptTaskMaterial>()
//                .eq(WmsOutReceiptTaskMaterial::getWmsOutReceiptTaskId, taskId));
//        if (ObjectUtil.isEmpty(list)) {
//            throw new JeecgBootException("出库任务无物料明细！");
//        }
//        WmsOutReceiptTask task = wmsOutReceiptTaskService.getById(taskId);
//        for (WmsOutReceiptTaskMaterial taskMaterial : list) {
//            LambdaQueryWrapper<WmsOutReceiptMaterial> tempQueryWrapper = new LambdaQueryWrapper<WmsOutReceiptMaterial>()
//                    .eq(WmsOutReceiptMaterial::getWmsOutReceiptId, wmsOutReceipt.getId())
//                    .eq(WmsOutReceiptMaterial::getWmsBasicMaterialId, taskMaterial.getWmsBasicMaterialId());
//            if (!StrUtil.isEmpty(taskMaterial.getBatchCode())) {
//                tempQueryWrapper.eq(WmsOutReceiptMaterial::getBatchCode, taskMaterial.getBatchCode());
//            }
//            List<WmsOutReceiptMaterial> realMaterialList = wmsOutReceiptMaterialService.list(tempQueryWrapper);
//            if (!CollectionUtil.isEmpty(realMaterialList)) {
//                //如果有这种物料，则比对任务数量和实际出库数量
//                WmsOutReceiptMaterial real = realMaterialList.get(0);
//                //获取未出库数量
//                BigDecimal unoutboundQuantity = taskMaterial.getUnoutboundQuantity();
//                if (ObjectUtil.isEmpty(unoutboundQuantity)) {
//                    //如果未出库数量为空，默认为计划出库数量
//                    unoutboundQuantity = taskMaterial.getPlanQuantity();
//                }
//                if (unoutboundQuantity.compareTo(real.getOutboundQuantity()) > 0) {
//                    taskOutFlag = false;
//                } else if (unoutboundQuantity.compareTo(real.getOutboundQuantity()) == 0) {
//                    taskOutFlag = true;
//                } else {
//                    taskOutFlag = true;
//                }
//            }
//        }
//        //重新获取更新过的出库任务-物料
//        List<WmsOutReceiptTaskMaterial> updatedList = wmsOutReceiptTaskMaterialService.list(new LambdaQueryWrapper<WmsOutReceiptTaskMaterial>()
//                .eq(WmsOutReceiptTaskMaterial::getWmsOutReceiptTaskId, taskId));
//        boolean anyMatch = updatedList.stream().anyMatch(o -> o.getUnoutboundQuantity().compareTo(BigDecimal.ZERO) != 0);
//        if(anyMatch) {
//            taskOutFlag=false;
//        }
//        if (!taskOutFlag) {
//            wmsOutReceiptTaskService.update(new LambdaUpdateWrapper<WmsOutReceiptTask>()
//                    .set(WmsOutReceiptTask::getOutboundStatus,OutboundStatusEnum.PART.getCode())
//                    .eq(WmsOutReceiptTask::getId,taskId)
//            );
//        }else {
//            wmsOutReceiptTaskService.update(new LambdaUpdateWrapper<WmsOutReceiptTask>()
//                    .set(WmsOutReceiptTask::getOutboundStatus,OutboundStatusEnum.ALL.getCode())
//                    .eq(WmsOutReceiptTask::getId,taskId)
//            );
//        }
//        return taskOutFlag;
//    }
}
